using UnityEngine;
public class PlayerPathFollowState : IState
{
    private Player player;

    public PlayerPathFollowState(Player player)
    {
        this.player = player;
    }

    public void OnEnter()
    {
        // 设置动画
        player.animator.SetFloat("Speed", 1);
    }

    public void OnUpdate()
    {
        if (!player.IsFollowingPath)
        {
            // 如果意外退出，可以切换到其他状态
            return;
        }

        // 获取当前目标点
        var targetCell = player.CurrentTargetCell;
        if (targetCell == null)
        {
            player.StopFollowingPath();
            return;
        }

        // 将目标单元格转换为世界坐标
        Vector3 targetPosition = player.PathTilemap.GetCellCenterWorld(targetCell.Value);
        Vector2 direction = (targetPosition - player.transform.position).normalized;

        // 移动
        player.MoveAlongPath(direction);

        // 检查是否到达当前目标点
        float distanceToTarget = Vector2.Distance(player.transform.position, targetPosition);
        if (distanceToTarget < Player.ReachedThreshold)
        {
            player.AdvanceToNextPathPoint();
            // 如果已经停止路径（例如在非循环模式下到达终点），则不再继续
            if (!player.IsFollowingPath)
            {
                // 状态机会在StopFollowingPath中切换到Idle，这里只需返回
                return;
            }
        }
    }

    public void OnFixedUpdate()
    {
        // 物理移动由Player的MoveAlongPath在FixedUpdate之前设置速度，所以这里可以留空
    }

    public void OnExit()
    {
        // 退出状态时重置动画或做一些清理
        player.animator.SetFloat("Speed", 0);
    }
}